import 'package:cached_network_image/cached_network_image.dart';
import 'package:flappy_search_bar/flappy_search_bar.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:jubobao/forum/JuBoForumModel.dart';
import 'package:jubobao/forum/JuBo_forum_services.dart';
import 'package:jubobao/order/JuBo_order.dart';
import 'package:jubobao/other/Widgets/JuBoFadeRoute.dart';
import 'package:jubobao/other/picturePreview/JuBoPhotoViewGalleryScreen.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'dart:math' as math;
class JuBoForum extends StatefulWidget {

  @override
  _JuBoForumState createState() => _JuBoForumState();
}

class _JuBoForumState extends State<JuBoForum> {

  TabController _tabController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('initState');
    _tabController = TabController(length:Choices.length , vsync: ScaffoldState());
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
    print('dispose');

  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      appBar: AppBar(
        leading: Icon(Icons.person,size: 28,) ,
        title: Container(
            child: TextField(
              decoration: InputDecoration(
                labelText: '  请输入搜索关键字',
                labelStyle: TextStyle(color: Colors.black54),
                border: InputBorder.none,
              ),
            ),
            height: 35,
            width: ScreenUtil.screenWidth - 100,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(8))
            ),
        ),
      ),
      body: NestedScrollView(

        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
            return <Widget>[
//              SliverAppBar(
//                  pinned: true,
//                  elevation: 0,
//                  expandedHeight: 200,
//                  flexibleSpace: FlexibleSpaceBar(
//                    title: Text('哈哈'),
//                    background: Image.network('http://img1.mukewang.com/5c18cf540001ac8206000338.jpg',fit: BoxFit.cover,),
//                ),
//              ),
              SliverPersistentHeader(
                  pinned: true,
                  delegate: StickyTabBarDelegate(
                      child:  TabBar(
                          indicatorWeight : 2,
                          indicatorColor : Colors.blue,
                          indicatorSize : TabBarIndicatorSize.tab,
                          labelColor : Colors.blue,
                          unselectedLabelColor : Colors.black87,
                          labelStyle : TextStyle(fontSize: 18),
                          unselectedLabelStyle : TextStyle(fontSize: 15),
                          dragStartBehavior : DragStartBehavior.start,
                          labelPadding : EdgeInsets.all(12),
                          controller : _tabController,
                          isScrollable : true,
                          tabs: Choices.map((e) => Text(e.title)).toList()),
                  )),
            ];
        },

        body: Column(
          children: <Widget>[

            Expanded(
              child: TabBarView(
                  controller: _tabController,
                  children: Choices.map((e) {
                    return JuboForumContent(e);
                  }).toList()
              ),
            ),

          ],
        ),
      ),
    );
  }
}

class Choice {
  final String title;
  final IconData icon;
  final int id;

  Choice({ this.title, this.icon,this.id});
}

 List<Choice> Choices = [
       Choice(title: '最新帖子',id:8),
       Choice(title: '最热帖子',id:10),
       Choice(title: '维修专区',id:9),
       Choice(title: '原片专区',id:1),
       Choice(title: '物流专区',id:2),
       Choice(title: '物流送货哪家强',id:3),
       Choice(title: '时事新闻',id:4),
       Choice(title: '搞笑内涵',id:5),
       Choice(title: '热门话题',id:6),
       Choice(title: '秀一秀',id: 7),
    ];

// ignore: must_be_immutable
class JuboForumContent extends StatefulWidget {

  Choice chioice;
  JuboForumContent(this.chioice);

  @override
  _JuboForumContentState createState() => _JuboForumContentState();
}

class _JuboForumContentState extends State<JuboForumContent> with AutomaticKeepAliveClientMixin{

  List <JuBoForumModel> _results ;
  int _index = 1;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData(widget.chioice.id,_index);
  }

  @override
  Widget build(BuildContext context) {

    if(_results == null){
      return Center(child: Text('正在加载中...'));
    }

    return  EasyRefresh(
              header: ClassicalHeader(
                  infoText: '加载中',
                  refreshReadyText : '松开刷新',
                  refreshingText : "正在刷新",
                  refreshedText : "刷新完成",
              ),

              onRefresh: () async {
                loadData(widget.chioice.id, 1);
              },
              onLoad: () async {
                _index ++;
                loadData(widget.chioice.id, _index);
              },
              child: ListView.separated(
                itemBuilder: (ctx, index) {
                  return content(true,_results[index]);
                },
                itemCount: _results.length,
                separatorBuilder : (ctx,index){
                  return Divider(
                    thickness: 1,
                  );
                },
              ),
          );
   }

  void loadData(id,index){

    JuBoForumServices.request(id,index).then((value){
      print(value);
      setState(() {
          if(index == 1){
            _results = value;
          }else{
            _results.addAll(value);
          }
      });
    });
  }

  Widget content(bool showPic,item){
    JuBoForumModel result = item;

    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
            child: Text(result.postTitle,style: TextStyle(fontSize: 17,color: Colors.black),),
          ),
          pics(item),
          bottom(result),
        ],
      ),
    );
  }

  Widget pics(item){
    JuBoForumModel result = item;
    List pics = result.pics.split(',');
    if(pics[0].length == 0) return Text('');

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: GridView(
          children: List.generate(pics.length, (index) {
            return GestureDetector(
              child: CachedNetworkImage(
                   fit: BoxFit.cover,
                   imageUrl: pics[index],
                   progressIndicatorBuilder: (context, url, downloadProgress){
                     return Icon(Icons.file_download);
                   },
                   errorWidget: (context, url, error) => Icon(Icons.error,size: 50,color: Colors.red,),
              ),
              onTap: (){
                Navigator.of(context).push(JuBoFadeRoute(
                  page: JuBoPhotoViewGalleryScreen(
                    images: pics,
                    index: index,
                  ),
                ));
              },
            );
          },),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8
          ),
          shrinkWrap: true,
          physics : NeverScrollableScrollPhysics()
      ),
    );
  }

  Widget bottom(result){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        iconImage(result),
        commentsSection(result)
      ],
    );
  }

  Widget iconImage(result)
  {
    String type = '';
    for(Choice c in Choices){
      if(c.id == result.postTypeID){
        type = c.title;
        break;
      }
    }
    var defalutImage = 'http://d.hiphotos.baidu.com/zhidao/pic/item/e61190ef76c6a7efd517f640fbfaaf51f3de66a6.jpg';
    if(result.userPic.toString().length > 0){
      defalutImage = result.userPic.toString();
    }

    return Row(
      children: <Widget>[
        ClipRRect(borderRadius: BorderRadius.circular(7),child: Image.network(defalutImage,width: 14,)),
        SizedBox(width: 4,),
        Text(result.nickname,style: TextStyle(color: Colors.blue,fontSize: 12),),
        SizedBox(width: 8,),
        Text(type,style: TextStyle(color: Colors.grey,fontSize: 12),),
      ],
    );
  }

  Widget commentsSection(result){
    return Row(
      children: <Widget>[
        commentsSectionItem('dianzan_off_icon','${result.giveUpCount}'),
        commentsSectionItem('huifu_icon','${result.pageView}'),
        commentsSectionItem('liulangshu_icon',result.replies.toString()),
      ],
    );
  }

  Widget commentsSectionItem(String iconName,String count){
    return Row(
      children: <Widget>[
        Image.asset('assets/forum/$iconName.png',width: 12,),
        SizedBox(width: 4,),
        Text(count),
        SizedBox(width: 8,),
      ],
    );
  }

}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
      final TabBar child;

      StickyTabBarDelegate({@required this.child});

      @override
      Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
        return Container( color: Colors.white,child: this.child);
      }

      @override
      double get maxExtent => this.child.preferredSize.height;

      @override
      double get minExtent => this.child.preferredSize.height;

      @override
      bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
        return true;
      }
}